package db;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class SQLScriptParser {

    private SQLScriptParser() {
    }

    /**
     * Read the SQL script from the specified file.
     * 
     * @param scriptFilePath
     *            Full path to the SQL script file.
     * @return A list of SQL statements.
     * @throws Exception
     */
    public static String[] readScript(File scriptFile) throws IOException {
        
        BufferedReader reader = new BufferedReader(new FileReader(scriptFile));
        String line = null;
        
        StringBuffer sqlStatements = new StringBuffer();
        List<String> specialStatements = new ArrayList<String>();
        while ((line = reader.readLine()) != null) {
            if (!line.startsWith("--") && line.length() > 0
                    && !line.startsWith("/") && !line.equals("commit;")) {
                if (line.endsWith("END;") || line.endsWith("end;")
                        || line.contains("&quot;")) {
                    if (line.contains("&quot;")) {
                        line = line.trim().substring(0,
                                line.trim().length() - 1);
                        specialStatements.add(line);
                    } else {
                        specialStatements.add(line);
                    }
                } else {
                    sqlStatements.append(" ");
                    sqlStatements.append(line);
                }
            }
            line = null;
        }

        String[] sqlStmts = sqlStatements.toString().split(";");

        String[] spslSqlStmts = 
            (String[]) specialStatements.toArray(new String[0]);

        String[] result = new String[sqlStmts.length + spslSqlStmts.length];
        System.arraycopy(sqlStmts, 0, result, 0, sqlStmts.length);
        System.arraycopy(spslSqlStmts, 0, result, sqlStmts.length,
                spslSqlStmts.length);

        return result;
    }
}
